<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{

	private $_id;	
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.*/
	public function authenticate()
	{
		 
		$record=Usuario::model()->findByAttributes(array('username'=>$this->username));
		//echo "$record->password ==".md5($this->password);die();
		if($record===null)
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		else if($record->password!==md5($this->password))
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
		{
			$this->_id=$record->rol_partido->partido->id;			
			$this->setState('title', $record->rol_partido->partido->nombre);
			$roles=$record->roles();
			$this->setState('roles',$roles);
			$this->setState('username',$record->username);
			$this->setState('defaultReturnUrl',$this->obtenerDefaultUrl($roles));		
			$this->errorCode=self::ERROR_NONE;
		}
		return !$this->errorCode;
	}
	
	private function obtenerDefaultUrl($roles){
		$arrRoles=explode(',',$roles);
		/*(1,'ADMINISTRADOR'),
		(2,'CATEDRATICO'),
		(3,'ASISTENTE_CATEDRA');*/
		$returnUrl='';
		if(in_array('CATEDRATICO', $arrRoles)){
			$returnUrl='catedratico';
		}
		else if(in_array('ASISTENTE_CATEDRA',$arrRoles)){
			$returnUrl='asistentecatedra';
		}
		else if(in_array('ADMINISTRADOR', $arrRoles)){
			$returnUrl='administracion';
		}
		return Yii::app()->createUrl($returnUrl);
	}

	public function getId()
	{
		return $this->_id;
	}


}